import { Action } from "@/mdesign-lib/mdesign-app.umd.js";
import { ChinaSouthZYSettingWindow } from "../customWindows/ChinaSouthZYSetting";
import { spawn } from "child_process";
import { ActionKey } from "@/mdesign-lib/mdesign-app.umd.js";
import { StorageKey } from "@/util/Storage";

export class ChinaSouthZYAction extends Action {
  keyName = "ChinaSouthZY" as ActionKey;
  desc = "ChinaSouthZY";

  async run() {
    const str = app.storage.get(StorageKey.ChinaSouthZYInfo) || "{}";
    const info = JSON.parse(str);
    const command = info.command;
    const params = info.params;
    const type = info.type;
    if (command) {
      const task = spawn(command, params ? [params] : [], { shell: type === "shell" });

      task.on("error", err => {
        console.error(err);
        app.$notify({ type: "error", title: "失败", message: "运行失败，请检查命令是否正确" });
      });

      task.stderr.on("data", data => {
        console.log("data", data);
        app.$notify({ type: "error", title: "失败", message: `stderr: ${data}` });
      });
    }
  }

  onSysMenuClick() {
    this.run();
  }
}

export class ChinaSouthZYSettingAction extends Action {
  keyName = "ChinaSouthZYSetting" as ActionKey;
  desc = "ChinaSouthZYSetting";

  async run() {
    const str = app.storage.get(StorageKey.ChinaSouthZYInfo) || "{}";
    const info = JSON.parse(str);
    const command = info.command;
    const params = info.params;
    const type = info.type;
    const res = await ChinaSouthZYSettingWindow.popup({ command, params, type });
    if (res.success) {
      const newInfo = {
        command: res.command,
        params: res.params,
        type: res.type
      };
      app.storage.set(StorageKey.ChinaSouthZYInfo, JSON.stringify(newInfo));
      app.$notify({ type: "success", title: "成功", message: "设置成功" });
    }
  }

  onSysMenuClick() {
    this.run();
  }
}
